/*
 * Copyright (c) 2018. cangoonline.net All Rights Reserved.
 * 类名称：TemplateUtils.java
 * 创建人：韩伟
 * 联系方式：hanwei@cangoonline.com
 */
package com.cango.mail.util;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

/**
 * Author: hanwei
 * CreateDate: 2019/9/11
 */
public class TemplateUtils {

    private static Logger logger = LoggerFactory.getLogger(TemplateUtils.class);

    private static VelocityEngine ve = null;
    private static String envName= "profiles/prd";


    public TemplateUtils(String name){
        envName=name;
    }

    static {
        Properties p = new Properties();
        String path = Thread.currentThread().getContextClassLoader().getResource("application.properties").getPath();
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("conf/template").getPath();
        try {
            p.load(new FileInputStream(new File(path)));
            p.put(Velocity.FILE_RESOURCE_LOADER_PATH, rootPath);
        } catch (IOException e) {
            logger.error("模板文件不存在", e);
        }
        //初始化并取得Velocity引擎
        ve = new VelocityEngine();
        ve.init(p);
    }

    /**
     * 应用模版生成文本
     *
     * @param tempPath
     * @param param
     * @return
     */
    public static String applyTemplate(String tempPath, Map<String, Object> param) {
        //取得velocity的上下文context
        VelocityContext context = new VelocityContext();
        //把数据填入上下文
        if (null != param && !param.isEmpty()) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                context.put(entry.getKey(), entry.getValue());
            }
        }
        context.put("envName",envName);
        // 输出流
        StringWriter writer = new StringWriter();
        // 转换输出
        ve.mergeTemplate(tempPath, "UTF-8", context, writer);
        return writer.toString();
    }

}
